package com.fingard.dsp.bank.directbank.spdb01.authforrec;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.Iterator;

public class XMLGetValueHelper {
    private static XMLGetValueHelper th;
    private Document doc;

    private XMLGetValueHelper() {
    }

    public static XMLGetValueHelper getInstance(String xml) throws DocumentException {
        if (th == null) {
            th = new XMLGetValueHelper();
        }
        th.init(xml);
        return th;
    }

    private void init(String xml) throws DocumentException {
        doc = DocumentHelper.parseText(xml);
    }

    /**
     * 获取节点key的Text
     *
     * @param key
     * @return
     */
    public String getString(String key) {
        Element root = doc.getRootElement();
        root = getValue(root, key);
        return root.getText();
    }

    /**
     * 获取节点Key[i]的Text
     *
     * @param key
     * @param i
     * @return
     */
    public String getString(String key, int i) {
        Element root = doc.getRootElement();
        root = getValue(root, key, new int[]{i});
        return root.getText();
    }

    /**
     * 获取节点Key[i]的Text，转换成Double
     *
     * @param key
     * @return
     */
    public Double getDouble(String key) {
        return Double.parseDouble(this.getString(key));
    }

    /**
     * 获取节点Key[i]的Text，转换成Integer
     *
     * @param key
     * @return
     */
    public Integer getInteger(String key) {
        return Integer.parseInt(this.getString(key));
    }

    /**
     * 获取节点key的Text
     *
     * @param root
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    private Element getValue(Element root, String key) {
        Element result = null;
        if (root.getName().equals(key)) {
            return root;
        }
        Iterator<Element> it = root.elementIterator();
        while (it.hasNext()) {
            Element item = it.next();
            result = getValue(item, key);
            if (result != null) {
                break;
            }
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    private Element getValue(Element root, String key, int[] deep) {
        Element result = null;
        if (root.getName().equals(key)) {
            if (deep[0] == 0) {
                return root;
            }
            deep[0]--;
        }

        Iterator<Element> it = root.elementIterator();
        while (it.hasNext()) {
            Element item = it.next();
            result = getValue(item, key, deep);
            if (result != null) {
                break;
            }
        }
        return result;
    }
}
